package com.xposed.aliproxy.http;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;

import com.xposed.aliproxy.utils.JsonUtil;
import com.xposed.aliproxy.utils.MyLog;
import com.xposed.aliproxy.utils.ParamConfig;
import com.xposed.aliproxy.utils.Utils;

import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.http.cookie.ClientCookie;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class HttpManager {

    public interface RequestCallback {
        void onFinish();

        void onFailMsg(String respCode, String respMsg);

        void onSuccess(JSONObject jSONObject);
    }

    /**
     * @return 拼接地址
     */
    public static String getSpliceUrl(Context context) {
        ParamConfig paramConfig = ParamConfig.getInstance(context);
        String host = paramConfig.getString("host", "");
        String port1 = paramConfig.getString("port1", "");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://");
        stringBuilder.append(host);
        stringBuilder.append(":");
        stringBuilder.append(port1);
        stringBuilder.append(CookieSpec.PATH_DELIM);
        String url = stringBuilder.toString();
        MyLog.printLog("HttpManager", url);
        return url;
    }

    /**
     * 开始登录
     */
    public static void requestLogin(final Activity activity, final String agentId, String agentKey, final String aliAccount, final RequestCallback callback) {
        final String lowerKey = agentKey.toLowerCase();
        new Thread(new Runnable() {
            public void run() {
                try {
                    Map hashMap = new HashMap();
                    hashMap.put("transType", "P002");
                    hashMap.put("agentID", agentId);
                    hashMap.put("inAccount", aliAccount);
                    hashMap.put("sign", Utils.signLogin(hashMap, lowerKey));
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(HttpManager.getSpliceUrl(activity));
                    stringBuilder.append("gateWayAgent");
                    JSONObject jSONObject = new JSONObject(HttpBase.request(stringBuilder.toString(), hashMap));
                    String respCode = jSONObject.getString("respCode");
                    String respMsg = jSONObject.getString("respMsg");
                    if ("00".equals(respCode)) {
                        onSuccess(activity, callback, jSONObject);
                    } else {
                        onFailMsg(activity, callback, respCode, respMsg);
                    }
                } catch (Throwable th) {
                    HttpManager.onFinish(activity, callback);
                }
                HttpManager.onFinish(activity, callback);
            }
        }).start();
    }

    /**
     * 升级检测
     */
    public static void requestUpdate(Activity activity, RequestCallback callback) {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(HttpManager.getSpliceUrl(activity));
            stringBuilder.append("download/android_version.txt");
            JSONObject jSONObject = new JSONObject(HttpBase.m2918a(stringBuilder.toString()));
            String a = JsonUtil.getString(jSONObject, ClientCookie.VERSION_ATTR);
            JsonUtil.getString(jSONObject, "message");
            JsonUtil.getString(jSONObject, "url");
            ParamConfig.getInstance(activity).putString("serverl_version", a);
            if (Integer.parseInt(a) > HttpManager.getVersionCode(activity)) {
                HttpManager.onSuccess(activity, callback, jSONObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int getVersionCode(Context context) throws NameNotFoundException {
        return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
    }

    public static String getVersionName(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    private static void onSuccess(Activity activity, final RequestCallback callback, final JSONObject jSONObject) {
        if (callback != null) {
            activity.runOnUiThread(new Runnable() {
                public void run() {
                    callback.onSuccess(jSONObject);
                }
            });
        }
    }

    private static void onFailMsg(Activity activity, final RequestCallback callback, final String respCode, final String respMsg) {
        if (callback != null) {
            activity.runOnUiThread(new Runnable() {
                public void run() {
                    callback.onFailMsg(respCode, respMsg);
                }
            });
        }
    }

    private static void onFinish(Activity activity, final RequestCallback callback) {
        if (callback != null) {
            activity.runOnUiThread(new Runnable() {
                public void run() {
                    callback.onFinish();
                }
            });
        }
    }
}
